package com.lsl.gulimall.product.service.impl;

import com.lsl.gulimall.product.entity.CategoryBrandRelationEntity;
import com.lsl.gulimall.product.service.CategoryBrandRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsl.common.utils.PageUtils;
import com.lsl.common.utils.Query;

import com.lsl.gulimall.product.dao.CategoryDao;
import com.lsl.gulimall.product.entity.CategoryEntity;
import com.lsl.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查出所有分类以及子分类，以树形结构组装起来
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {

        //1、查出所有分类
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);

        //2、组装成父子的树形结构

        //2.1）、找到所有的一级分类
        List<CategoryEntity> level1Menus = categoryEntityList.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0)
                .map((menu) -> {
                    menu.setChildren(getChildren(menu, categoryEntityList));
                    return menu;
                })
                .sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                }).collect(Collectors.toList());
        return level1Menus;
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid().equals(root.getCatId());
        }).map(categoryEntity -> {
            //1、找到子菜单
            categoryEntity.setChildren(getChildren(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //2、菜单的排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

    @Override
    public void deleteMenusByIds(List<Long> asList) {
        //TODO 删除菜单之前先判断是否在其他地方有引用该菜单
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        ArrayList<Long> paths = new ArrayList<>();
        List<Long> ParentPaths = getParentPath(catelogId, paths);
        Collections.reverse(ParentPaths);
        return (Long[]) ParentPaths.toArray(new Long[ParentPaths.size()]);
    }

    @Override
    public void updateDetail(CategoryEntity category) {
        Long catId = category.getCatId();
        QueryWrapper<CategoryBrandRelationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("catelog_id", catId);
        int count = categoryBrandRelationService.getBaseMapper().selectCount(queryWrapper);
        if(count>0){
            List<CategoryBrandRelationEntity> categoryBrandRelationEntities = categoryBrandRelationService.getBaseMapper().selectList(queryWrapper);
            if (categoryBrandRelationEntities != null && categoryBrandRelationEntities.size() > 0) {
                categoryBrandRelationEntities.stream().map(
                        (item) -> {
                            item.setCatelogName(category.getName());
                            return item;
                        }
                ).collect(Collectors.toList());
                categoryBrandRelationService.updateBatchById(categoryBrandRelationEntities);
            }
        }

        this.baseMapper.updateById(category);
    }


    public List<Long> getParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity categoryEntity = this.baseMapper.selectById(catelogId);
        if (categoryEntity != null) {
            if (categoryEntity.getParentCid()!=0) {
                getParentPath(categoryEntity.getParentCid(), paths);
            }
        }
        return paths;
    }
}